#include <pace/P99Component.h>
#include <pace/MsgTubeI.h>
//#include <InterfaceMsg.h>
//#include <DBConnection.h>

#include "DataAccess.h"

#include "WatchEventHandlerI.h"

#define SLEEP 250000 // 250 ms

using namespace std;
using namespace iPlature;
using namespace Monitor;

class WebTagCache : public P99Component
{
public:
  void PostInitCall()
  {
    LOG log(__FUNCTION__);
    const string serverName = "WebTagCache";

    Ice::PropertiesPtr icePropPtr = Component::instance()->properties();
    log.Info() << "## 0. 项目配置初始化成功" << endl;

    CDataAccess::GetInstance()->Initialize();
    log.Info() << "## 1. 数据库连接池初始化成功" << endl;

    WatchWithDataInterfacePtr watchEvent = new CWatchEventHandlerI();
    this->subscribe("Tag/WatchWithDataTopic", watchEvent);
    log.Info() << "## 2. Tag 服务注册成功" << endl;

    //iDA::ConnectionProxyPtr cnnPtr = iDA::ConnectionPool::getConnection();
    //iDA::Command cmd(cnnPtr.get(), "select TAGNAME, TAGVALUE from UACS_WEB_TAG_CACHE;");
	//iDA::Command cmd(cnnPtr.get(), "select TAGNAME, TAGVALUE from UACS_WEB_TAG_CACHE");
	iDA::Command cmd(&CDataAccess::GetInstance()->m_DBCon, "select TAGNAME, TAGVALUE from UACS_WEB_TAG_CACHE");

    map<string, string> cachedTagPairs;
    TAGNAMEARRAY tagNameArray;
    string data = "";
    cmd.Execute();
    while (cmd.FetchNext())
    {
      const string tagname = cmd.Field(1).AsString();
      const string tagvalue = cmd.Field(2).AsString();
      cachedTagPairs.insert(make_pair(tagname, tagvalue));
      tagNameArray.push_back(tagname);
    }

    while (true)
    {
      int nCheckedTags = 0;
      int nUpdatedTags = 0;

      TAGVALUEMAP tagValueMap;
      Tag::GetInst().GetActual(tagNameArray, tagValueMap);
      nCheckedTags = tagValueMap.size();

      TAGVALUEMAP::iterator it;
      string body = "";
      for (it = tagValueMap.begin(); it != tagValueMap.end(); it++)
      {
        const string key = StringHelper::ToString(it->first);
        const string val = StringHelper::ToString(it->second);
        if (cachedTagPairs[key].compare(val) != 0)
        {
          body += "when TAGNAME = '" + key + "' then '" + val + "' ";
          cachedTagPairs[key] = val;
          nUpdatedTags++;
        }
      }
      if (body.compare("") != 0)
      {
        string sql = "update UACS_WEB_TAG_CACHE set TAGVALUE = case " + body + "else TAGVALUE end";
	iDA::Command cmd(&CDataAccess::GetInstance()->m_DBCon, sql);
        cmd.Execute();
        //iDA::Command cmdUpdater(&CDataAccess::GetInstance()->m_DBCon, sql);
        //cmdUpdater.Execute();
	//	cnnPtr.get()->Commit();
      }

      if (nCheckedTags != tagNameArray.size())
      {
        log.Error() << "some tags are missing!"
                    << " nChecked = " << nCheckedTags
                    << " , totalTags = " << tagNameArray.size()
                    << " nUpdateTags = " << nUpdatedTags
                    << endl;
      }
      usleep(SLEEP);
    }
  }

  ByteSeq HandleMessage(const ByteSeq &ParamBuffer)
  {
    return ParamBuffer;
  }
};

PACE_SERVER_INSTALL(WebTagCache);
